namespace SB2.Core;

public class DisplayColumnDto
{
    /// <summary>
    /// 显示名称
    /// </summary>
    /// <value></value>
    public string DisplayName { get; set; }
    /// <summary>
    /// 列名
    /// </summary>
    /// <value></value>
    public string ColumnName { get; set; }
    /// <summary>
    /// 是否显示 可配置
    /// </summary>
    /// <value></value>
    public bool Display { get; set; }
    /// <summary>
    /// 隐藏显示 不可配置
    /// </summary>
    /// <value></value>
    public bool Hide { get; set; }
    /// <summary>
    /// 实际 字段名称
    /// </summary>
    /// <value></value>
    public string FieldName { get; set; }
    /// <summary>
    /// 排序
    /// </summary>
    /// <value></value>
    public int Order { get; set; }
    /// <summary>
    /// 是否支持筛选
    /// </summary>
    /// <value></value>
    public bool Seachable { get; set; }
    /// <summary>
    /// 数据类型
    /// </summary>
    /// <value></value>
    public DisplayDtoDataType DataType { get; set; }
    /// <summary>
    /// 数据源
    /// </summary>
    /// <value></value>
    public object Options { get; set; }

    /// <summary>
    /// 获取显示列 全部项目
    /// TODO  权限内项目 取交集
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static DisplayColumnListDto GetDisplayColumnDto<T>() where T : class
    {
        var types = typeof(T);
        var datas = types.GetMembers()
        .Select(m => new { a = m, b = m.GetCustomAttributes(typeof(DisplayDtoAttribute), false) })
        .Where(m => m.b != null && m.b.Any())
        .Select(m =>
        {
            var temp = (DisplayDtoAttribute)m.b.FirstOrDefault();
            return Init(temp, m.a.Name);
        })
        .ToList();
        return new DisplayColumnListDto(datas);
    }
    static DisplayColumnDto Init(DisplayDtoAttribute attribute, string name)
    {
        var dto = attribute.Adapt<DisplayColumnDto>();
        dto.ColumnName = name;
        dto.Display = !dto.Hide;
        if (string.IsNullOrEmpty(dto.FieldName)) dto.FieldName = dto.ColumnName;
        return dto.InitDataSourse(attribute.DataSourse);
    }
    DisplayColumnDto InitDataSourse(string DataSourse)
    {
        switch (this.DataType)
        {
            case DisplayDtoDataType.Enums:
                InitEnumsDataSourse(DataSourse);
                break;
            default: break;

        }
        return this;
    }

    void InitEnumsDataSourse(string DataSourse)
    {
        var type = App.Assemblies
         .Select(m => m.GetType(DataSourse))
         .FirstOrDefault(m => m != null);
        List<object> options = new List<object>();
        foreach (var a in Enum.GetValues(type))
        {
            options.Add(new { label = type.GetField(a.ToString()).GetDescription(), value = (int)a });
        }
        this.Options = options;

    }
}
